//
// Created by zlxx on 2022/10/21.
//
#include "TupleValue.h"

RC TupleValue::cell_at(int index, TupleCell &cell) const
{
  if (index < 0 || index >= static_cast<int>(field_exprs_.size())) {
    LOG_WARN("invalid argument. index=%d", index);
    return RC::INVALID_ARGUMENT;
  }
  auto field_meta = field_exprs_[index].field().meta();
  cell.set_type(field_meta->type());
  cell.set_data(record_.data() + field_meta->offset());
  cell.set_length(field_meta->len());
  return RC::SUCCESS;
}
RC TupleValue::find_cell(const Field &field, TupleCell &cell) const
{
  const char *table_name = field.table_name();
  if (0 != strcmp(table_name, table_->name())) {
    return RC::NOTFOUND;
  }
  int i = 0;
  const char *field_name = field.field_name();
  for (auto field_expr : field_exprs_) {
    auto f = field_expr.field();
    if (0 == strcmp(field_name, f.field_name())) {
      return cell_at(i, cell);
    }
    i++;
  }
  return RC::NOTFOUND;
}
void TupleValue::set_schema(const Table *table, const std::vector<FieldMeta> *fields)
{
  table_ = table;
  for (const FieldMeta &field : *fields) {
    field_exprs_.emplace_back(table, &field);
  }
}
const Table *TupleValue::table() const
{
  return table_;
}
Record TupleValue::record()
{
  return record_;
}
void TupleValue::set_record(const Record &record)
{
  record_ = record;
}